package interceptor;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import entity.role.MyResource;
import service.role.IRoleService;

public class PermissionInterceptor extends HandlerInterceptorAdapter {

	@Resource
	private IRoleService roleServiceImpl;

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		String userId = (String) request.getSession().getAttribute(request.getSession().getId());
		String uri = request.getRequestURI();
		Boolean flag = false;
		// 查询当前登录用户有的权限
		List<MyResource> currentUserAllMyResources = roleServiceImpl.getCurrentUserResourcesByUserId(userId);
		for (MyResource myResource : currentUserAllMyResources) {
			if (uri.indexOf(myResource.getUrl()) > 0) {
				flag = true;
			}
		}
		if (!flag) {
			JSONObject data = new JSONObject();
			data.put("msg", "没有权限");
			data.put("flag", false);
			response.getWriter().write(data.toJSONString());
		}
		return flag;
	}
}
